# -*- coding: utf-8 -*-

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html

from scrapy.exceptions import DropItem
from pymongo import MongoClient
from logging import getLogger
import re

logger = getLogger(__name__)
class BooksPipeline(object):
    def process_item(self, item, spider):
        if spider.name == 'jd':
            item = self._clean_data_jd(item)
            return item
        if spider.name == 'dd':
            item = self._clean_data_dd(item)
            return item
        if spider.name == 'ymx':
            item = self._clean_data_ymx(item)
            return item
        else:
            raise DropItem


    def _clean_data_jd(self, item):
        item['book_img'] = 'https:' + item['book_img'] if item['book_img'] is not None else None
        item['book_author'] = item['book_author'] if len(item['book_author']) > 0 else None
        return item

    def _clean_data_dd(self, item):
        item['b_cate'] = [i.strip() for i in item['b_cate'] if len(i.strip())>0][0]
        item['m_cate'] = [i.strip() for i in item['m_cate'] if len(i.strip())>0][0]
        return item

    def _clean_data_ymx(self, item):
        item['book_author'] = [i.strip() for i in item['book_author'] if len(i.strip())>0]
        book_author = ''
        for i in item['book_author']:
            book_author += i
        item['book_author'] = book_author
        item['book_title'] = [i.strip() for i in item['book_title'] if len(i.strip())>0]
        book_title = ''
        for i in item['book_title']:
            book_title += i
        item['book_title'] = book_title
        item['book_cate'] = item['book_cate'].strip() if item['book_cate'] is not None else None
        item['book_heat'] = re.findall(r'\d+',item['book_heat'])[0] if item['book_heat'] is not None else None
        item['book_price'] = item['book_price'].strip()[1:] if item['book_price'] is not None else None
        item['book_press'] = item['book_press'].strip() if item['book_press'] is not None else None
        item['book_publish_date'] = re.findall(r'.*?\((.*?)\)', item['book_press'])[0] if item['book_press'] is not None else None
        item['book_press'] = re.findall(r'(.*?)\(.*?\)',item['book_press'])[0].strip() if item['book_press'] is not None else None
        item['book_evaluate'] = item['book_evaluate'] if len(item['book_evaluate'])>0 else None
        item['book_evaluate'] = [i.strip() for i in item['book_evaluate'] if len(i.strip())>0] if item['book_evaluate'] is not None else None
        return item

class MongoPipeline(object):
    def __init__(self, mongo_url, mongo_db):
        self.mongo_url = mongo_url
        self.mongo_db = mongo_db
        self.db = None
        self.client = None

    @classmethod
    def from_crawler(cls, crawler):
        return cls(
            mongo_url=crawler.settings.get('MONGO_URL'),
            mongo_db=crawler.settings.get('MONGO_DB')
        )

    def open_spider(self, spider):
        self.client = MongoClient(self.mongo_url)
        self.mongo_db = self.client[self.mongo_db]

    def process_item(self, item, spider):
        if spider.name == 'jd':
            logger.warning('Jdbook:%s保存到MongoDB成功'% item['book_name'])
            name = item.__class__.__name__
            self.mongo_db[name].update({'book_sku':item['book_sku']},{'$set':dict(item)},True)
            return item
        if spider.name == 'dd':
            logger.warning('Ddbook:%s保存到MongoDB成功'% item['book_name'])
            name = item.__class__.__name__
            self.mongo_db[name].update({'book_name':item['book_name']},{'$set':dict(item)},True)
            return item
        if spider.name == 'ymx':
            logger.warning('Ymxbook:%s保存到MongoDB成功' % item['book_title'])
            name = item.__class__.__name__
            self.mongo_db[name].update({'book_title': item['book_title']}, {'$set': dict(item)}, True)
            return item
        else:
            raise DropItem

    def close(self, spider):
        self.client.close()

